﻿using System;
using System.Linq;
using System.Text;
using System.Windows;
using Microsoft.Surface.Presentation.Controls;
using System.Xml.Linq;
using System.Net;
using System.IO;
using Microsoft.Surface.Presentation.Controls.Primitives;
using System.Windows.Markup;
using System.Windows.Controls;
using System.Windows.Input;

namespace WikipediaSurfaceBrowser
{
    public partial class Search : SurfaceUserControl
    {
        private ApplicationSettings _settings = new ApplicationSettings();
        private ScatterView _mainScatterView;
        private string SEARCH_URL_WIKIPEDIA = "http://{0}.wikipedia.org/w/api.php?action=opensearch&search={1}&format=xml&limit={2}";
        private string SEARCH_URL_COMMONS = "http://commons.wikimedia.org/w/api.php?action=opensearch&search={0}&format=xml&limit={1}";
        private string RESOURCES_FLAGS = @"pack://application:,,,/Resources/Flags";
        private string _wikiLanguage;

        public readonly static string TAG_WIKIPEDIA = "Wikipedia";
        public readonly static string TAG_COMMONS = "Commons";
        private readonly static XNamespace O = "http://opensearch.org/searchsuggest2";


        public Search(ScatterView mainScatterView)
        {
            InitializeComponent();
            this._mainScatterView = mainScatterView;

            foreach (string l in _settings.AvailableWikipediaLanguages.Split(new char[] { ';' }))
            {
                SurfaceRadioButton st = new SurfaceRadioButton();
                st.Template = (ControlTemplate) Resources["languageRadioButton"];
                st.Tag = l;
                st.Checked += new RoutedEventHandler(SurfaceToggleButton_Checked);
                st.Content = XamlReader.Parse(String.Format("<Image xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" Width=\"40\" Height=\"27\" Source=\"{0}/{1}.png\" />", RESOURCES_FLAGS, l));
                spLanguages.Children.Add(st);
            }

            if (spLanguages.Children.Count > 0)
            {
                ((SurfaceRadioButton)spLanguages.Children[0]).IsChecked = true;
            }
        }

        public String WikiLanguage { get { return _wikiLanguage; } }


        private void btnSearch_Click(object sender, RoutedEventArgs e)
        {
            if (String.IsNullOrEmpty(txtSearch.Text) || (sender.GetType() != typeof(SurfaceButton)))
            {
                return;
            }

            SurfaceButton b = sender as SurfaceButton;

            if (b.Tag == null)
            {
                return;
            }

            StartSearch(b.Tag.ToString());
        }

        private void StartSearch(string tag)
        {
            string searchUrl = null;

            if (tag.Equals(TAG_WIKIPEDIA))
            {
                searchUrl = String.Format(SEARCH_URL_WIKIPEDIA,
                                            _wikiLanguage,
                                            Uri.EscapeUriString(txtSearch.Text),
                                            _settings.SearchCount);
            }
            else if (tag.Equals(TAG_COMMONS))
            {
                searchUrl = String.Format(SEARCH_URL_COMMONS,
                                            Uri.EscapeUriString(txtSearch.Text),
                                            _settings.SearchCount);
            }

            if (String.IsNullOrEmpty(searchUrl))
            {
                return;
            }


            XDocument searchResult = XDocument.Parse(ReadFromWeb(searchUrl));        

            string[] topics = (from t in searchResult.Descendants(O + "Text")
                               select t.Value).ToArray<string>();

            StringBuilder sb = new StringBuilder();

            foreach (string topic in topics)
            {
                sb.Append("[[" + topic + "]]");
                sb.AppendLine();
            }

            WikiToXaml.WikiToXamlConvertor wtxc = new WikiToXaml.WikiToXamlConvertor();

            _mainScatterView.Items.Add(new ScatterViewItem()
            {
                Width = _settings.TopicWidth,
                Height = _settings.TopicHeight,
                CanScale = false,
                Content = new WikiTopic()
                {
                    DocumentContent = wtxc.ConvertToFlowDocument(sb.ToString()),
                    TitleLabel = txtSearch.Text,
                    SearchType = tag,
                    WikiLanguage = _wikiLanguage
                }
            });
        }

        private string ReadFromWeb(string url)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri(url));
            request.Accept = "text/xml";

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            StreamReader data = new StreamReader(response.GetResponseStream(), System.Text.Encoding.UTF8);
            return data.ReadToEnd();
        }       

        private void SurfaceToggleButton_Checked(object sender, RoutedEventArgs e)
        {
            SurfaceRadioButton currentLanguageButton = (SurfaceRadioButton)sender;
            _wikiLanguage = currentLanguageButton.Tag.ToString();           
        }

        private void txtSearch_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (e.Key != Key.Enter)
            {
                return;
            }

            StartSearch(TAG_WIKIPEDIA);
            StartSearch(TAG_COMMONS);
        }
    }
}